package com.withoutwords.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.withoutwords.R;
import com.withoutwords.engine.BitmapCache;
import com.withoutwords.engine.Common;
import com.withoutwords.engine.Game;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.Guess;
import com.withoutwords.engine.Round;
import com.withoutwords.engine.social.SocialUser;
import com.withoutwords.ui.custom.MyCustomButton;
import com.withoutwords.ui.custom.WordsLayout;
import com.withoutwords.ui.drawing.DrawingControllerFactory;

public class ViewerPlayingActivity extends BasePlayinyActivity {

	
	

	boolean bRoundReady = false;
	Handler uiHandler = null;
	protected byte[] drawingData;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewer_playing);

		/* special case here cancels invitation notification on creation */
		Common.cancelNotification(this, Common.invitationRecievedNotificatoin);

		notificationId = Common.actingRecievedNotificatoin;
		Intent intent = getIntent();
		boolean bgameJoined = intent.getBooleanExtra(Common.gameJoined, false);
		game = (Game) intent.getSerializableExtra("game");
		String gameId = "";
		if (game != null) {
			gameId = game.getGameId();
		} else {
			gameId = intent.getStringExtra(Common.gameIdCode);
		}
		if (gameId != null && !gameId.equalsIgnoreCase("")) {

			if (!bgameJoined) {
				GameController controller = GameController.getInstance();
				controller.joinGame(gameId);

			} else {
				GameController.getInstance().setCurrentGame(gameId);
				game = GameController.getInstance().getCurrentGame();
			}

		}/* else {

			// Load Game data
			GameController.getInstance().setCurrentGame(gameId);
			// GameController.getInstance().addGame(game);
		}*/
		// game = (Game) intent.getSerializableExtra("game");
		if (game == null) {
			game = GameController.getInstance().getCurrentGame();

		}
		initRound(intent);
		uiHandler = new Handler();

		ImageButton btn = (ImageButton) findViewById(R.id.btnShowGuesses);
		btn.setOnClickListener(this);
		btn.setEnabled(bRoundReady);
		btn = (ImageButton) findViewById(R.id.btnEditGuess);
		btn.setOnClickListener(this);
		btn.setEnabled(bRoundReady);
		ImageButton btn2 = (ImageButton) findViewById(R.id.btnShowPlayers);
		btn2.setOnClickListener(this);

		updateGuessesNumber();
		initMediaInfoViews(false);

		MyCustomButton btnSubmitGuess = (MyCustomButton) findViewById(R.id.btnSubmitGuess);
		if (btnSubmitGuess != null) {
			btnSubmitGuess.setOnClickListener(this);
		}
		setDrawingData(intent);
		// initViews();
		if (bgameJoined) {
			GameController.getInstance().loadLastActingData();
		}

		// playSound(soundResId);
	}

	@Override
	protected void setBitmaps() {
		// TODO Auto-generated method stub
		super.setBitmaps();
		setLayoutBitmap(R.id.lyViewer, R.drawable.drawing);

	}

	@Override
	protected void unsetBitmaps() {
		// TODO Auto-generated method stub
		super.unsetBitmaps();
		unsetLayoutBitmaps(R.id.lyViewer);

	}

	@Override
	protected void releaseBitmaps() {
		// TODO Auto-generated method stub
		super.releaseBitmaps();
		/*
		 * BitmapCache .getCacheInstance().deleteDrawable(R.drawable.intro);
		 */
		BitmapCache.getCacheInstance().deleteDrawable(R.drawable.drawing);
	}

	private void setDrawingData(Intent intent) {
		playSound(R.raw.sound_drawing_drums);
		// TODO Auto-generated method stub
		drawingData = intent.getByteArrayExtra(Common.drawingBytes);
		if (drawingData != null) {
			try {
				Log.e("recieved Drawing Bytes", new String(drawingData));
				if (mDrawingController == null) {
					initDrawingViews();

				}
			
				mDrawingController.setCurrentDrawing(drawingData);
				bringEditGuessToFront();
				

			} catch (Exception e) {
				if (e != null && e.getMessage() != null) {
					Log.e("Exception in image", e.getMessage());
				}
			}

		}
	}

	void initRound(Intent intent) {
		Round r = (Round) intent.getSerializableExtra(Common.roundCode);
		if (r != null) {
			round = r;

		}
		if (round == null) {
			if (game != null) {
				round = game.getCurrentRound();
			}
		}

		bRoundReady = (round != null && !round.getRoundId()
				.equalsIgnoreCase(""));

	}

	void updateSelectedWord(int selnd) {
		WordsLayout wly = (WordsLayout) findViewById(R.id.text_container_id);
		wly.setSelectedWord(selnd);
		wly.invalidate();
	}

	@Override
	public void onNewDataRecieved(final Intent intent) {
		super.onNewDataRecieved(intent);
		if (intent != null) {

			if (game == null) {
				game = (Game) intent.getSerializableExtra("game");
			}
			initRound(intent);
			if (round != null) {
				selectedWordIndex = round.getCurrentWordIndex();
			} else {
				selectedWordIndex = 0;
			}

			selectedWordIndex = intent.getIntExtra(Common.wordIndex,
					selectedWordIndex);

			uiHandler.post(new Runnable() {

				@Override
				public void run() {

					int notId = intent.getIntExtra(Common.notificationId, -1);
					if (notId == Common.guessApprovedNotificatoin) {
						playSound(R.raw.sound_guess_approved);
						updateGuessesNumber();
					}
					

					// why initializing every thing here ????
					// this happens with every drawing recieved
					initMediaInfoViews(false);
					setDrawingData(intent);
					updateSelectedWord(selectedWordIndex);
					ImageButton btn = (ImageButton) findViewById(R.id.btnShowGuesses);
					btn.setEnabled(bRoundReady);
					btn = (ImageButton) findViewById(R.id.btnEditGuess);
					btn.setEnabled(bRoundReady);
				}
			});
		}

	}

	private void submitguess() {
		EditText ed = (EditText) findViewById(R.id.editGuess);

		String editText = ed.getText().toString();
		String[] guessStrings = editText.split(" ");
		Guess guess = new Guess();

		if(game != null)
		{
		guess.gameId = game.getGameId();
		if (guessStrings.length == 1) {
			guess.wordIndex = selectedWordIndex;
		} else {
			guess.wordIndex = -1;
		}

		guess.wordGuess = editText;
		}

		ed.setText("");
		Common.hideKeyboard(this, ed);
		GameController.getInstance().submitGuess(guess);
		updateGuessesNumber();

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		/*
		 * case R.id.btnJoin: { GameController.getInstance().joinGame(game);
		 * v.setVisibility(View.INVISIBLE); break; }
		 */
		case R.id.btnSubmitGuess: {
			submitguess();
			LinearLayout ly = (LinearLayout) findViewById(R.id.lyEditGuess);
			ly.setVisibility(View.INVISIBLE);
			View editView = findViewById(R.id.btnEditGuess);
			editView.setVisibility(View.VISIBLE);

			break;
		}
		case R.id.btnShowGuesses: {
			showGuesses();
			break;
		}
		case R.id.btnEditGuess: {
			showEditGuess();

			break;
		}
		}

	}

	@Override
	protected void initDrawingViews() {
		// TODO Auto-generated method stub
		// super.initDrawingViews();
		if (mDrawingController == null) {
			mDrawingController = DrawingControllerFactory.createDrawingView();
		}
		FrameLayout fly = (FrameLayout) findViewById(R.id.canvas_container_id);
		mDrawingController.initializeViews(this, fly, true);
		bringEditGuessToFront();

	}

	private void bringEditGuessToFront() {
		LinearLayout ly = (LinearLayout) findViewById(R.id.lyEditGuess);
		if (ly != null) {
			ly.bringToFront();
		}
		ImageButton editBtn = (ImageButton) findViewById(R.id.btnEditGuess);
		if (editBtn != null) {
			editBtn.bringToFront();

		}
	}

	void showEditGuess() {
		LinearLayout ly = (LinearLayout) findViewById(R.id.lyEditGuess);
		ly.setVisibility(View.VISIBLE);
		View v = findViewById(R.id.btnEditGuess);
		v.setVisibility(View.INVISIBLE);
		bringEditGuessToFront();
	}

	@Override
	public void onWordPressed(int wordIndex) {
		selectedWordIndex = wordIndex;
		showEditGuess();

	}

	@Override
	protected byte[] getDrawingBitmapData() {
		// TODO Auto-generated method stub
		return mDrawingController.getDrawingBytesToShare();
	}

}
